const connectFetch = () => {
  ctrl = new AbortController()
  fetchEventSource('http://127.0.0.1:8080/v1/chat/completions', {
      method: 'POST',
      body: JSON.stringify({
          prompt: 'Lorem ipsum',
          max_tokens: 20,
          stream: true,
      }),
      signal: ctrl.signal,
      onopen: () => {
          console.log('Connection successful.')
      },
      onclose: () => {
          console.log('Connection closed.')
      },
      onmessage: (delta) => {
          let prefix = 'data: '
          if (!delta.startsWith(prefix)) {
              return
          }
          delta = delta.slice(prefix.length)
          delta = delta.replace(/\n$/, '')
          if (delta === '[DONE]\n') {
              return
          }
          divTyping.innerText += delta
      }
  })
}

const closeSSE = () => {
  if (ctrl) {
      ctrl.abort()
      ctrl = null
  }
}

const fetchEventSource = (url, options) => {
  fetch(url, options).then(resp => {
      if (resp.status === 200) {
          options.onopen && options.onopen()
          return resp.body
      }
  }).then(rb => {
      const reader = rb.getReader()
      const push = () => {
          // done 为数据是否接收完成 boolean 值
          // value 为接收到的数据, Uint8Array 格式
          return reader.read().then(({done, value}) => {
              if (done) {
                  options.onclose && options.onclose()
                  return
              }
              options.onmessage && options.onmessage(new TextDecoder().decode(value))
              return push()
          });
      }
      // 开始读取流信息
      return push()
  }).catch((e) => {
      options.error && options.error(e)
  })
}